//
//  ShopListChooseViewController.m
//  GetPowerDBO
//
//  Created by 周博 on 2017/7/6.
//  Copyright © 2017年 BogoZhou. All rights reserved.
//

#import "ShopListChooseViewController.h"
#import "ShopListChooseTableViewCell.h"
#import "BorderHelper.h"

#define kCellName @"ShopListChooseTableViewCell"


@interface ShopListChooseViewController ()<UITableViewDelegate,UITableViewDataSource,UISearchControllerDelegate,UISearchResultsUpdating>
{
    
}
@property (nonatomic,retain) UISearchController *searchController;


@property (nonatomic,strong) NSMutableArray *searchListArry;

@end

@implementation ShopListChooseViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self UISetting];
    [self creatSearchBar];
}

- (void)UISetting{
//    _dataArray = [NSMutableArray array];
    _searchListArry = [NSMutableArray array];
    
    UITapGestureRecognizer *tableViewGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(commentTableViewTouchInSide)];
    tableViewGesture.numberOfTapsRequired = 1;
    tableViewGesture.cancelsTouchesInView = NO;
    [_tableView addGestureRecognizer:tableViewGesture];
}

- (void)commentTableViewTouchInSide{
    [_searchController.searchBar resignFirstResponder];
}

- (void)creatSearchBar{
    //创建UISearchController
    self.searchController = [[UISearchController alloc]initWithSearchResultsController:nil];
    //设置代理
    self.searchController.delegate= self;
    self.searchController.searchResultsUpdater = self;
    
    //包着搜索框外层的颜色
    self.searchController.searchBar.barTintColor = kColorFrom0x(0xf5f5f5);
    
    [self.searchController.searchBar setBackgroundImage:[UIImage new]];
    
    UITextField *textField = [self.searchController.searchBar valueForKey:@"_searchField"];
    textField.layer.masksToBounds = YES;
    textField.layer.borderWidth = 0.5;
    textField.layer.borderColor = [kColorFrom0x(0xdedee0) CGColor];
    textField.layer.cornerRadius = kButtonCornerRadius ;
    [BorderHelper setOnlyUnderLineColor:kColorFrom0x(0xeeeeee) view:self.searchController.searchBar];
    
    
    self.searchController.searchBar.tintColor = kGreenColor;
    
    
    
    
    //提醒字眼
    self.searchController.searchBar.placeholder= @"请输入关键字搜索";
    
    //搜索时，背景变暗色
    self.searchController.dimsBackgroundDuringPresentation = NO;
    //搜索时，背景变模糊
    //    self.searchController.obscuresBackgroundDuringPresentation = NO;
    
    //点击搜索的时候,是否隐藏导航栏
    self.searchController.hidesNavigationBarDuringPresentation = NO;
    
    //位置
    self.searchController.searchBar.frame = CGRectMake(self.searchController.searchBar.frame.origin.x, self.searchController.searchBar.frame.origin.y, self.searchController.searchBar.frame.size.width, 44.0);
    
    // 添加 searchbar 到 headerview
    self.tableView.tableHeaderView = self.searchController.searchBar;
    
    self.definesPresentationContext=YES;
    
    
}

#pragma mark - 点击事件

- (IBAction)backButtonClick:(UIButton *)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - tableViewDelegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (_searchController.active) {
        return _searchListArry.count;
    }
    return _dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    ShopListChooseTableViewCell *cell = (ShopListChooseTableViewCell *)[tableView dequeueReusableCellWithIdentifier:kCellName];
    ShopModel *model;
    if (self.searchController.active) {
         model = _searchListArry[indexPath.row];
        cell.labelName.text = model.name;
        [cell.imageViewHeader sd_setImageWithURL:[NSURL URLWithString:model.img_url] placeholderImage:[UIImage imageNamed:@""]];
    }else{
        model = _dataArray[indexPath.row];
        cell.labelName.text = model.name;
        [cell.imageViewHeader sd_setImageWithURL:[NSURL URLWithString:model.img_url] placeholderImage:[UIImage imageNamed:@""]];
    }
    UIImage *image ;
    if (model.store_type.integerValue == 0) {//无
        image = [UIImage imageNamed:@"wuIcon"];
    }else if (model.store_type.integerValue == 1){//wifi
        image = [UIImage imageNamed:@"28_WiFi"];
    }else if (model.store_type.integerValue == 4){
        image = [UIImage imageNamed:@"28_mimasuo"];
    }
    
    cell.imageViewType.image = image;
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    ShopModel *model ;
    if (self.searchController.active) {
        model = _searchListArry[indexPath.row];
    }else{
        model = _dataArray[indexPath.row];
    }
    
//    if ([_delegate respondsToSelector:@selector(sendValue:)]) { // 如果协议响应了sendValue:方法
        [_delegate sendValue:model]; // 通知执行协议方法
//    }
    [self.navigationController popViewControllerAnimated:YES];
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 50;
}

#pragma mark - searchBarDelegate

//谓词搜索过滤
-(void)updateSearchResultsForSearchController:(UISearchController *)searchController {
    
    NSLog(@"updateSearchResultsForSearchController");
    NSString *searchString = [self.searchController.searchBar text];
    NSPredicate *preicate = [NSPredicate predicateWithFormat:@"SELF CONTAINS[c] %@", searchString];
    if (self.searchListArry!= nil) {
        [self.searchListArry removeAllObjects];
    }
    
    NSMutableArray *nameArray = [NSMutableArray array];
    for (ShopModel *model in _dataArray) {
        [nameArray addObject:model.name];
    }
    
    //过滤数据
    
    NSArray *searchedArray = [NSArray array];
    
    searchedArray = [NSArray arrayWithArray:[nameArray filteredArrayUsingPredicate:preicate]];
    for (unsigned i = 0; i < [searchedArray count]; i++){
        for (ShopModel *model in _dataArray) {
            if ([[searchedArray objectAtIndex:i] isEqualToString:model.name]) {
                if ([_searchListArry containsObject:model] == NO){
                    [_searchListArry addObject:model];
                }
            }
        }
    }
    
    //刷新表格
    [_tableView reloadData];
}



#pragma mark - UISearchControllerDelegate代理
//测试UISearchController的执行过程

- (void)willPresentSearchController:(UISearchController *)searchController
{
    NSLog(@"willPresentSearchController");
}

- (void)didPresentSearchController:(UISearchController *)searchController
{
    NSLog(@"didPresentSearchController");
    
    //    [self.view addSubview:self.searchController.searchBar];
}

- (void)willDismissSearchController:(UISearchController *)searchController
{
    NSLog(@"willDismissSearchController");
}

- (void)didDismissSearchController:(UISearchController *)searchController
{
    NSLog(@"didDismissSearchController");
}

- (void)presentSearchController:(UISearchController *)searchController
{
    NSLog(@"presentSearchController");
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
